let storage = bui.storage();
let org;
let language,translate
loader.define(function (require, exports, module, global) {
    let pageview = {
        init() {
            translate = global.translate
            language = storage.get("language", 0)
            if (!language) {
                language = 'chinese_simplified'
            }
            try {
                translate.selectLanguageTag.show = false;
                let curLanguage = translate.language.getCurrent()
                if (curLanguage !== language) {
                    translate.changeLanguage(language)
                }
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            if (language === "chinese_simplified") {
                router.$("#J_Form").css("font-size", "")
                router.$(".bui-input").css("font-size", "")
                router.$("#advertTab").css("font-size", "")
            } else {
                router.$("#J_Form").css("font-size", ".22rem")
                router.$(".bui-input").css("font-size", ".22rem")
                router.$("#advertTab").css("font-size", ".3rem")
            }

            let uiLoading = bui.loading({
                appendTo:"#loadingAdvertise",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"加载中。。。",
                callback: function (argument) {
                }
            });
            let uiLoadingBtn = bui.loading({
                appendTo:"#loadingAdvertise",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"提交中。。。",
                callback: function (argument) {
                }
            });
            uiLoading.show()

            router.$("#advertiseEditFh").click(function () {
                router.load({ url: "pages/advertiseList/advertiseList.html"});
            })

            let user = storage.get("user",0)
            let token = storage.get("token",0)

            let imgStr
            let zyUser
            let article, articleZj, articleStr
            let uiList
            let cate
            let validStartDate
            let validEndDate
            let params = module.props;
            let id = params.id;

            let titleStatus = true, weightStatus = true
            let citySelect2
            let country = '', city = ''
            let countryId, cityId

            // 标题
            let title = bui.input({
                id: "#adTitleInput",
                showIcon: false,
                onInput: function(e) {
                    if (e.target.value.length > 40) {
                        titleStatus = false
                        router.$("#titleTs").html("标题最多40个字符");
                    }
                    return true;
                }
            })
            // 显示权重
            let weight = bui.input({
                id: "#weightInput",
                showIcon: false,
                onInput: function(e) {
                    let rule = /^\d{0,4}$/
                    if (!rule.test(e.target.value)) {
                        weightStatus = false
                        router.$("#weightTs").html("显示权重只能为整数最大9999")
                        return false;
                    } else {
                        weightStatus = true
                        router.$("#weightTs").html("")
                    }
                    return true;
                }
            })

            // 自定义居中弹出框
            let selectedDialog = bui.dialog({
                id: "#selectedDialog",
                height: 400,
                // mask: false,
                callback: function(e) {}
            });

            router.$("#articleK").click(function () {
                if (city) {
                    selectedDialog.open()
                } else {
                    bui.alert('请先选择地区')
                }
            })

            router.$("#searchArticle").click(function () {
                uiList.replace({
                    data:{city: city,
                        country: country,
                        title: router.$("#articleTitleSearch").val()
                    }
                });
            })
            router.$("#advertiseConfirm").click(function () {
                article = articleZj
                router.$("#article").html(articleStr)
            })

            router.$("#chooseCityShow").on("click", function() {
                citySelect2.show();
            })

            let start_datepicker_input = bui.pickerdate({
                handle: "#start_datepicker_input",
                bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                // input 显示的日期格式
                formatValue: "yyyy-MM-dd hh:mm:ss",
                callback: function(e) {
                    validStartDate = this.value()
                }
                // 如果不需要按钮,设置为空
                // buttons: [{name:"取消"}]
            });
            let end_datepicker_input = bui.pickerdate({
                handle: "#end_datepicker_input",
                bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                // input 显示的日期格式
                formatValue: "yyyy-MM-dd hh:mm:ss",
                callback: function(e) {
                    validEndDate = this.value()
                }
                // 如果不需要按钮,设置为空
                // buttons: [{name:"取消"}]
            });

            // 拍照上传
            let $facePhoto = router.$("#buiPhotoAd");
            let $uploadBtn = router.$("#picK");
            let uiUpload = bui.upload({
                showProgress: true,
                // needNative: false
            });
            // 上拉菜单 js 初始化:
            bui.actionsheet({
                trigger: "#btnUploadAd",
                buttons: [{ name: "拍照上传", value: "camera" }, { name: "从相册选取", value: "photo" }],
                callback: function(e) {
                    let ui = this;
                    let val = router.$(e.target).attr("value");
                    switch (val) {
                        case "camera":
                            ui.hide();
                            uiUpload.add({
                                "from": "camera",
                                // "needCompress": true, // 1.5.3新增压缩
                                // "width": 300,
                                "destinationType": "file", //  file | blob | data
                                "onSuccess": function(val, data) {
                                    // 直接调用start上传图片
                                    this.start({
                                        url: global.api.advertisePicUpload,
                                        data: {
                                            file: this.data().file
                                        },
                                        onSuccess: function(data) {
                                            // bui.alert(data);
                                            if (data.code == '200') {
                                                router.$('#btnUploadAd').hide()
                                                $uploadBtn.show()
                                                imgStr = data.data.image
                                                // $uploadBtn.html(templatePhoto("http://127.0.0.1:8333/profile/advert/" + data.data.image, uiUpload))
                                                $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/advert/" + data.data.image, uiUpload))
                                            } else {
                                                bui.alert(data.msg)
                                            }
                                        },
                                        onFail: function(data) {
                                            bui.alert("图片上传失败！")
                                        },
                                    })
                                }
                            })
                            break;
                        case "photo":
                            ui.hide();
                            uiUpload.add({
                                "from": "",
                                "onSuccess": function(val, data) {
                                    this.start({
                                        url: global.api.advertisePicUpload,
                                        data: {
                                            file: this.data().file
                                        },
                                        onSuccess: function(data) {
                                            // bui.alert(data);
                                            if (data.code == '200') {
                                                router.$('#btnUploadAd').hide()
                                                imgStr = data.data.image
                                                // $uploadBtn.html(templatePhoto("http://127.0.0.1:8333/profile/advert/" + data.data.image, uiUpload))
                                                $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/advert/" + data.data.image, uiUpload))
                                                $uploadBtn.show()
                                            } else {
                                                bui.alert(data.msg)
                                            }
                                        },
                                        onFail: function(data) {
                                            bui.alert("图片上传失败！")
                                        },
                                    })
                                }
                            })
                            break;
                        case "cancel":
                            ui.hide();
                            break;
                    }
                }
            })

            // 选择图片文件
            $facePhoto.on("click", ".icon-removefill", function(e) {
                var $item = router.$(this).parents(".span1");
                var index = $item.attr("data-index");
                var name = $item.attr("data-name");

                // 删除对应的上传数据
                uiUpload.remove(name);
                // 删除dom显示
                // $item.remove();
                $item.empty();
                // $("#picK").empty()
                e.stopPropagation();

                imgStr = ""
                router.$('#btnUploadAd').show()
                $uploadBtn.hide()
            })


            //查询所属用户
            bui.ajax({
                url: global.api.getZyUserList,
                data: {id: id},
                method: "POST",
                headers: {Token: token}
            }).then(function(res){
                let zyUsers = res.data

                let html = ""
                zyUsers.forEach(value => {
                    html += '<div class="span1">\n' +
                        '                                <input id="'+value.id+'" type="checkbox" class="bui-check" name="zyUser" value="'+value.id+'" check="'+value.fname+'" uncheck="'+value.fname+'">\n' +
                        '                            </div>'
                })
                router.$("#zyUser").html(html)

                if (id) {
                    //查询广告内容
                    bui.ajax({
                        url: global.api.getAdvertiseInfoByEdit,
                        data: {id: id},
                        method: "POST"
                    }).then(function(res){
                        let data = res.data
                        router.$("#adtTitle").val(data.title)

                        if (data.img || data.imgUrl) {
                            router.$('#btnUploadAd').hide()
                            $uploadBtn.show()
                            if (data.img) {
                                imgStr = data.img
                                $uploadBtn.html(templatePhotoDefault(global.api.baseurl + "profile/58Upload/advert/" + imgStr))
                            } else if (data.imgUrl) {
                                imgStr = data.imgUrl
                                $uploadBtn.html(templatePhotoDefault(imgStr))
                            }
                        }

                        if (data.place) {
                            if (data.place.indexOf("1") > -1) {
                                router.$("#place1").attr("checked", "checked")
                            }
                            if (data.place.indexOf("2") > -1) {
                                router.$("#place2").attr("checked", "checked")
                            }
                            if (data.place.indexOf("3") > -1) {
                                router.$("#place3").attr("checked", "checked")
                                router.$("#userK").show()
                            }
                        }

                        let countryStr = ''
                        let cityStr = ''
                        if (data.countryStr) {
                            countryStr = data.countryStr
                        }
                        if (data.cityStr) {
                            cityStr = data.cityStr
                        }

                        //查询地区
                        bui.ajax({
                            url: global.api.termTree,
                            method: "POST",
                            headers: {Token: token}
                        }).then(function(res){
                            let dqList = res.data
                            if (dqList) {
                                // 设置值
                                citySelect2 = bui.levelselect({
                                    data: dqList,
                                    title: "所在地区",
                                    trigger: ".selected-vals",
                                    level: 2,
                                    field: {
                                        name: "description",
                                        data: ["children"],
                                    },
                                    value: [countryStr, cityStr],
                                    onChange: function (e, currentData, nextData) {
                                        let sj = $(e.target).parent()
                                        let name = sj.children("input").attr("xzname")
                                        let id = sj.children("input").attr("xzid")
                                        let lx = sj.children("input").attr("lx")
                                        if (name.indexOf('-') < 0) {
                                            if (lx == '2') {
                                                country = name
                                                countryId = id
                                            } else if (lx == '3') {
                                                city = name
                                                cityId = id

                                                router.$('#adCountryTs').html('')

                                                uiList.replace({
                                                    data:{city: cityId,
                                                        country: countryId
                                                    }
                                                });
                                            }
                                        }
                                    }
                                })
                            }
                            try {
                                translate.execute();
                            }catch (e) {
                                console.log("切换语言报错")
                            }
                        })

                        if (data.validStartDateStr) {
                            validStartDate = data.validStartDateStr
                            router.$("#start_datepicker_input").val(validStartDate)
                        } else {
                            start_datepicker_input.empty()
                        }
                        if (data.validEndDateStr) {
                            validEndDate = data.validEndDateStr
                            router.$("#end_datepicker_input").val(validEndDate)
                        }else {
                            end_datepicker_input.empty()
                        }

                        router.$("#weight").val(data.weight)

                        if (data.zyUserStr) {
                            let zys = data.zyUserStr.split(',')
                            $.each(zys, function (index, value) {
                                router.$("#" + value).attr("checked", "checked")
                            })
                        }

                        article = data.article
                        if (data.articleStr) {
                            router.$("#article").html(data.articleStr)
                        }

                        uiList = bui.list({
                            id: "#selectedArticleScrollList",
                            url: global.api.getArticleList,
                            pageSize: 10, // 当pageSize 小于返回的数据大小的时候,则认为是最后一页,接口返回的数据最好能返回空数组,而不是null
                            data: {
                                city: data.cityId,
                                country: data.countryId
                            },
                            //如果分页的字段名不一样,通过field重新定义
                            field: {
                                page: "page",
                                size: "limit",
                                data: "data"
                            },
                            callback: function(e) {
                                // e.target 为你当前点击的元素
                                // e.currentTarget 为你当前点击的handle 整行
                                let id = router.$(e.currentTarget).attr("id")
                                articleStr = router.$(e.currentTarget).attr("name")
                                router.$(".articleChildren").css({
                                    "background":"white",
                                    "color":"black"
                                });
                                if (articleZj != id) {
                                    router.$(e.currentTarget).css({
                                        "background":"blue",
                                        "color":"white"
                                    })
                                    articleZj = id
                                } else {
                                    articleZj = ""
                                    articleStr = "请选择文章"
                                }
                            },
                            template: function(data) {
                                let html = "";
                                data.forEach(function(el, index) {

                                    if (article && article == el.id)  {
                                        html += '<li class="bui-btn bui-box articleChildren" id="'+el.id+'" name="'+el.title+'" style="background: blue; color: white">\n'
                                    } else {
                                        html += '<li class="bui-btn bui-box articleChildren" id="'+el.id+'" name="'+el.title+'" style="color: black;">\n'
                                    }

                                        html +='                            <div style="min-height: 60px">\n'+
                                            '                                <p style="font-size: 0.28rem;margin-bottom: 0.22rem">'+el.title+'</p>\n'+
                                        '                            </div>\n'+
                                        '                        </li>'
                                });
                                setTimeout(function () {
                                    try {
                                        translate.execute();
                                    }catch (e) {
                                        console.log("切换语言报错")
                                    }
                                },1000)
                                return html;
                            }
                        })

                        uiLoading.stop()
                        try {
                            translate.execute();
                        }catch (e) {
                            console.log("切换语言报错")
                        }
                    })
                    router.$("#advertTab").html("编辑广告")
                } else {
                    router.$("#place1").attr("checked", "checked")
                    router.$("#advertTab").html("新增广告")
                    start_datepicker_input.empty()
                    end_datepicker_input.empty()

                    //查询地区
                    bui.ajax({
                        url: global.api.termTree,
                        method: "POST",
                        headers: {Token: token}
                    }).then(function(res){
                        let dqList = res.data
                        if (dqList) {
                            // 设置值
                            citySelect2 = bui.levelselect({
                                data: dqList,
                                title: "所在地区",
                                trigger: ".selected-vals",
                                level: 2,
                                field: {
                                    name: "description",
                                    data: ["children"],
                                },
                                onChange: function (e, currentData, nextData) {
                                    let sj = $(e.target).parent()
                                    let name = sj.children("input").attr("xzname")
                                    let id = sj.children("input").attr("xzid")
                                    let lx = sj.children("input").attr("lx")
                                    if (name.indexOf('-') < 0) {
                                        if (lx == '2') {
                                            country = name
                                            countryId = id
                                        } else if (lx == '3') {
                                            city = name
                                            cityId = id

                                            router.$('#adCountryTs').html('')

                                            if (uiList) {
                                                uiList.replace({
                                                    data:{city: cityId,
                                                        country: countryId
                                                    }
                                                });
                                            } else {
                                                uiList = bui.list({
                                                    id: "#selectedArticleScrollList",
                                                    url: global.api.getArticleList,
                                                    pageSize: 10, // 当pageSize 小于返回的数据大小的时候,则认为是最后一页,接口返回的数据最好能返回空数组,而不是null
                                                    data: {
                                                        city: cityId,
                                                        country: countryId
                                                    },
                                                    //如果分页的字段名不一样,通过field重新定义
                                                    field: {
                                                        page: "page",
                                                        size: "limit",
                                                        data: "data"
                                                    },
                                                    callback: function(e) {
                                                        // e.target 为你当前点击的元素
                                                        // e.currentTarget 为你当前点击的handle 整行
                                                        let id = router.$(e.currentTarget).attr("id")
                                                        articleStr = router.$(e.currentTarget).attr("name")
                                                        router.$(".articleChildren").css({
                                                            "background":"white",
                                                            "color":"black"
                                                        });
                                                        if (articleZj != id) {
                                                            router.$(e.currentTarget).css({
                                                                "background":"blue",
                                                                "color":"white"
                                                            })
                                                            articleZj = id
                                                        } else {
                                                            articleZj = ""
                                                            articleStr = "请选择文章"
                                                        }
                                                    },
                                                    template: function(data) {
                                                        let html = "";
                                                        data.forEach(function(el, index) {
                                                            if (article && article == el.id)  {
                                                                html += '<li class="bui-btn bui-box articleChildren" id="'+el.id+'" name="'+el.title+'" style="background: blue; color: white">\n'
                                                            } else {
                                                                html += '<li class="bui-btn bui-box articleChildren" id="'+el.id+'" name="'+el.title+'" style="color: black;">\n'
                                                            }

                                                            html +='                            <div style="min-height: 60px">\n'+
                                                                '                                <p style="font-size: 0.28rem;margin-bottom: 0.22rem">'+el.title+'</p>\n'+
                                                                '                            </div>\n'+
                                                                '                        </li>'
                                                        });
                                                        setTimeout(function () {
                                                            try {
                                                                translate.execute();
                                                            }catch (e) {
                                                                console.log("切换语言报错")
                                                            }
                                                        },1000)
                                                        return html;
                                                    }
                                                })
                                            }
                                        }
                                    }
                                }
                            })
                        }

                        try {
                            translate.execute();
                        }catch (e) {
                            console.log("切换语言报错")
                        }
                        uiLoading.stop()
                    })
                }

                try {
                    translate.execute();
                }catch (e) {
                    console.log("切换语言报错")
                }
            })

            router.$("input[name='place']").change(function () {
                if (router.$(this).val() == '3') {
                    router.$("#userK").show()
                } else {
                    router.$("#userK").hide()
                }
            })

            router.$("#fbAdvertise").click(function () {
                if (titleStatus && weightStatus && validStartDate && validEndDate && country && city) {
                    // bui.btn("#fbAdvertise").submit(function(loading) {
                    uiLoadingBtn.show()
                        let place = '';
                        $.each(router.$("input[name='place']:checked"), function (index, value) {
                            place += router.$(value).val() + ','
                        })
                        if (place) {
                            place = place.substring(0, place.length - 1)
                        }
                        let zyUser = '';
                        if (place.indexOf('3') > -1) {
                            $.each(router.$("input[name='zyUser']:checked"), function (index, value) {
                                zyUser += router.$(value).val() + ','
                            })
                            if (zyUser) {
                                zyUser = zyUser.substring(0, zyUser.length - 1)
                            }
                        }
                        if (id) {
                            bui.ajax({
                                url: global.api.editAdvertise,
                                data: {title: title.value(),img: imgStr, city: city, country: country,weight: weight.value(),place: place,id: id,
                                    cate: cate, validStartDateStr: validStartDate, validEndDateStr: validEndDate, user: user.userId, zyUser: zyUser, article: article},
                                method: "POST"
                            }).then(function(res){
                                if (res.code == '200') {
                                    // 修改数据
                                    bui.confirm("修改成功！", function(e) {
                                        //this 是指点击的按钮
                                        var text = router.$(e.target).text();

                                        if (text == "确定") {
                                            router.load({ url: "pages/advertiseList/advertiseList.html"});
                                        }
                                        this.close()
                                    });
                                } else {
                                    bui.alert("修改失败！")
                                }
                                // loading.stop()
                                uiLoadingBtn.stop()
                            })
                        } else {
                            bui.ajax({
                                url: global.api.insertAdvertise,
                                data: {title: title.value(),img: imgStr, city: city, country: country,weight: weight.value(),place: place,
                                    cate: cate, validStartDateStr: validStartDate, validEndDateStr: validEndDate, user: user.userId, zyUser: zyUser},
                                method: "POST"
                            }).then(function(res){
                                if (res.code == '200') {
                                    // 修改数据
                                    bui.confirm("新增成功！", function(e) {
                                        //this 是指点击的按钮
                                        var text = router.$(e.target).text();

                                        if (text == "确定") {
                                            router.load({ url: "pages/advertiseList/advertiseList.html"});
                                        }
                                        this.close()
                                    });
                                } else {
                                    bui.alert("新增失败！")
                                }
                                // loading.stop()
                                uiLoadingBtn.stop()
                            })
                        }
                    // })
                } else {
                    if (!country || !city) {
                        router.$('#adCountryTs').html('所属地区不可为空！')
                    }
                    bui.alert("数据不符合格式，请检查！")
                }
            })
            try {
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
        }
    };

    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function getDate(dateStr) {
    return new Date(Date.parse(dateStr.replace(/-/g, "/")));
}

function templatePhoto(url, uiUpload) {
    return `<div class="span1" data-index="${uiUpload.currentIndex()}" data-name="${uiUpload.currentName()}">
                <div class="bui-upload-thumbnail"><img src="${url}" alt="" style="width: 100%; height: 1.4rem"/><i class="icon-removefill"></i></div>
            </div>`
}
function templatePhotoDefault(url) {

    return `<div class="span1" data-index="-1" data-name="default.jpg">
                <div class="bui-upload-thumbnail"><img src="${url}" alt="" style="width: 100%; height: 1.4rem"/><i class="icon-removefill"></i></div>
            </div>`
}
